<script setup lang='ts'>
import type { FormItemRule } from 'element-plus'
import type { OptionsType, PlusColumn } from 'plus-pro-components'

import { useAddProject, useGetProjectInfo, useUpdateProject } from '@fl/api/man-api/pricing-tool'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

const props = withDefaults(defineProps<{
    newAllList?: any
}>(), {
    newAllList: () => {},
})

const { newAllList } = toRefs(props)
const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<number | string>('id', { required: true })
const formRef = ref()

type IState = {
    biddingEnterprise: string
    categoryId: number | string
    categoryName: string
    id?: number | string
    projectDate: string
    projectName: string
}

const initialState = {
    biddingEnterprise: '',
    categoryId: '',
    categoryName: '',
    id: '',
    projectDate: '',
    projectName: '',
}
const state = ref<IState>(cloneDeep(initialState))
const title = computed(() => {
    return id.value ? '编辑组合商品类目' : '新建组合商品类目'
})

const { isPending: addProjectPending, mutate } = useAddProject()
const { isPending: updateProjectPending, mutate: updateProjectMutate } = useUpdateProject()
const { data: projectInfo, isLoading } = useGetProjectInfo(id as any)
const isPending = computed(() => {
    return addProjectPending.value || updateProjectPending.value
})

const disabledFieldProps = computed(() => {
    return {
        disabled: !!id.value,
    }
})

watchEffect(() => {
    if (id.value) {
        if (projectInfo.value) {
            state.value.id = projectInfo.value.id
            state.value.biddingEnterprise = projectInfo.value.biddingEnterprise
            state.value.categoryId = projectInfo.value.categoryId
            state.value.categoryName = projectInfo.value.categoryName
            state.value.projectDate = projectInfo.value.projectDate
            state.value.projectName = projectInfo.value.projectName
        }
    }
})

const columns: PlusColumn[] = [
    {
        fieldProps: disabledFieldProps,
        label: '组合商品类目',
        options: newAllList as OptionsType,
        prop: 'categoryId',
        valueType: 'select',
    },
    {
        fieldProps: {
            maxlength: 100,
        },
        label: '项目名称',
        prop: 'projectName',
    },
    {
        fieldProps: {
            maxlength: 50,
        },
        label: '招标单位',
        prop: 'biddingEnterprise',
    },
    {
        fieldProps: {
            'value-format': 'YYYY-MM-DD',
        },
        label: '招标时间',
        prop: 'projectDate',
        valueType: 'date-picker',
    },
]

function validateProjectName(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入项目名称'))
    }
    if (pattern.test(value))
        callback(new Error('项目名称不允许输入空格'))

    else
        callback()
}

function validateOrganization(_rule: FormItemRule, value: string, callback: Fn): void {
    const pattern = /\s/
    if (!value) {
        callback(new Error('请输入招标单位'))
    }
    if (pattern.test(value))
        callback(new Error('招标单位不允许输入空格'))

    else
        callback()
}

const rules = {
    biddingEnterprise: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateOrganization,
        },
    ],
    categoryId: [
        {
            message: '请选择商品类目',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    projectDate: [
        {
            message: '请选择招标时间',
            required: true,
            trigger: ['blur', 'change'],
        },
    ],
    projectName: [
        {
            required: true,
            trigger: ['blur', 'change'],
            validator: validateProjectName,
        },
    ],
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            ...state.value,
            categoryName: newAllList.value.find(item => item.value === state.value.categoryId)?.label || '',
        }
        console.log(params, 'params')
        const fn = id.value ? updateProjectMutate : mutate

        fn(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="600"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="120"
                  :rules="rules"
                  :has-footer="false"
        />

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
